package com.mxpio.erp.equipment.controller;

import cn.hutool.core.date.DateUtil;
import com.mxpio.erp.common.enums.EquipmentEnums;
import com.mxpio.erp.common.equipment.entity.EquipmentRepair;
import com.mxpio.erp.common.equipment.entity.EquipmentRepairOperation;
import com.mxpio.erp.common.equipment.entity.EquipmentRepairPickupLine;
import com.mxpio.erp.common.equipment.entity.EquipmentRepairTransfer;
import com.mxpio.erp.common.equipment.service.EquipmentEqpBasicsService;
import com.mxpio.erp.common.equipment.service.EquipmentRepairOperationService;
import com.mxpio.erp.common.equipment.service.EquipmentRepairService;
import com.mxpio.erp.common.equipment.service.EquipmentRepairTransferService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.service.UserService;
import com.mxpioframework.system.service.DictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * @Description: 设备维修
 * @Author: chenqiang
 * @Date: 2021-09-23
 * @Version: V1.0
 */

@Slf4j
@Tag(name = "EquipmentRepairController", description = "设备维修接口")
@RestController
@RequestMapping("/erp/equipment/spotrepair")
public class EquipmentRepairController {

    @Autowired
    private EquipmentRepairService equipmentRepairService;

    @Autowired
    private EquipmentRepairOperationService equipmentRepairOperationService;

    @Autowired
    private EquipmentRepairTransferService equipmentRepairTransferService;

    @Autowired
    private EquipmentEqpBasicsService equipmentEqpBasicsService;

    @Resource
    private UserService sysUserMapper;
    @Resource
    private DictService sysDictService;

    /**
     * 分页列表查询
     *
     * @param criteria
     * @param pageNo
     * @param flag
     * @param applyStart
     * @param applyEnd
     * @param planRepairStart
     * @param planRepairEnd
     * @param failureTime
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "设备维修分页列表", description = "设备维修-分页列表查询", method = "GET")
    public Result<Page<EquipmentRepair>> queryPageList(@Parameter(description = "查询参数") Criteria criteria,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "flag", defaultValue = "apply") String flag,
                                                       @RequestParam(name = "applyStart", required = false) String applyStart, //申请开始时间
                                                       @RequestParam(name = "applyEnd", required = false) String applyEnd, //申请结束时间
                                                       @RequestParam(name = "planRepairStart", required = false) String planRepairStart,//计划开始时间
                                                       @RequestParam(name = "planRepairEnd", required = false) String planRepairEnd, //计划结束时间
                                                       @RequestParam(name = "failureTime", required = false) String failureTime,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<EquipmentRepair> pageList = equipmentRepairService.getTpmRepairIPage(criteria, page, flag, applyStart, applyEnd, planRepairStart, planRepairEnd, failureTime, req);
        return Result.OK(pageList);
    }

    @GetMapping("/page")
    @Operation(summary = "repair列表", description = "获取repair列表（分页）", method = "GET")
    public Result<Page<EquipmentRepair>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        List<Object> criterions = criteria.getCriterions();
        Boolean sevenDaysPastQuery = false;
        if (!criterions.isEmpty()){
            Iterator<Object> iterator = criterions.iterator();
            while(iterator.hasNext()){
                Object next = iterator.next();
                if (next instanceof SimpleCriterion){
                    SimpleCriterion simpleCriterion = (SimpleCriterion)next;
                    if (StringUtils.equals(simpleCriterion.getFieldName(),"sevenDaysPastQuery")){
                        sevenDaysPastQuery = true;
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        if (sevenDaysPastQuery){
            Iterator<Object> iterator = criterions.iterator();
            while(iterator.hasNext()){
                Object next = iterator.next();
                if (next instanceof SimpleCriterion){
                    SimpleCriterion simpleCriterion = (SimpleCriterion)next;
                    if (StringUtils.equals(simpleCriterion.getFieldName(),"createTime")){
                        iterator.remove();
                    }
                }
            }
            String today = DateUtil.formatDate(new Date());
//            criteria.addCriterion("createTime",Operator.LE,DateUtil.parseDateTime(today+" "+"23:59:59"));
//            criteria.addCriterion("createTime",Operator.GT, DateUtils.addDays(DateUtil.parseDateTime(today+" "+"00:00:00"),-6));
//            调整为只查当天
            criteria.addCriterion("createTime",Operator.GT,DateUtil.parseDateTime(today+" "+"00:00:00"));
            criteria.addCriterion("createTime",Operator.LE,DateUtil.parseDateTime(today+" "+"23:59:59"));
        }

        Page<EquipmentRepair> pageResult = equipmentRepairService.listPage(EquipmentRepair.class, page, criteria);
        return Result.OK(pageResult);
    }

    /**
     * 对维修工单根据TargetId进行过滤操作
     * @param criteria
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/page/dedup")
    @Operation(summary = "对repair列表进行去重操作", description = "获取repair列表（分页），并进行去重操作", method = "GET")
    public Result<Page<EquipmentRepair>> pageDeduplication(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentRepair> pageResult = equipmentRepairService.getTheNumberOfFaultyDevices(criteria, page);
        return Result.OK(pageResult);
    }

    /**
     *  获取当前用户协助的repair列表（分页）
     * @param criteria
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/page/userAssist")
    @Operation(summary = "获取当前用户协助的repair列表（分页）", description = "获取当前用户协助的repair列表（分页）", method = "GET")
    public Result<Page<EquipmentRepair>> pageUserAssist(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentRepair> pageResult = equipmentRepairService.userAssistedTickets(criteria, page);
        return Result.OK(pageResult);
    }


    @GetMapping("/queryRepairingList")
    @Operation(summary = "设备维修-维修中列表查询", description = "设备维修-维修中列表查询", method = "GET")
    public Result<?> queryRepairingList() {
        List<EquipmentRepair> list = equipmentRepairService.queryRepairingList();
        return Result.OK(list);
    }

    @GetMapping("/code/{bizNo}")
    @Operation(summary = "设备维修-根據編號查詢工單信息(带催办子表信息)", description = "设备维修-根據編號查詢工單信息(带催办子表信息)", method = "GET")
    public Result<?> getByOrderCode(@PathVariable(name = "bizNo", required = true) String bizNo) {
        EquipmentRepair repair= equipmentRepairService.getByOrderCode(bizNo);
        return Result.OK(repair);
    }


    /**
     * 添加
     *
     * @param equipmentRepair
     * @return
     */
    @PostMapping(value = "/add")
    @Operation(summary = "设备维修-添加", description = "设备维修-添加", method = "POST")
    public Result<?> add(@RequestBody EquipmentRepair equipmentRepair) {
        //当申请为设备时需要判断是否维保中
        /*if ("eqp".equals(equipmentRepair.getTargetType())) {
            EquipmentEqpBasics eqpBasics = equipmentEqpBasicsService.getById(EquipmentEqpBasics.class, equipmentRepair.getTargetId());
            if (eqpBasics != null && eqpBasics.getStatus() == 40) {
                return Result.error("名称：" + eqpBasics.getEqpName() + ",编码：" + eqpBasics.getEqpCode() + ",正在为维保中。。。不能进行维修！");
            }
        }*/
        equipmentRepairService.saveRepair(equipmentRepair);
        return Result.OK("维修申请成功！");
    }
    @RequestMapping (value = "/evaluate")
    @Operation(summary = "设备维修-评价", description = "设备维修-评价")
    public Result<?> evaluate(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.evaluate(equipmentRepair);
    }

    @RequestMapping (value = "/statement")
    @Operation(summary = "设备维修-结单", description = "设备维修-结单")
    public Result<?> statement(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.statement(equipmentRepair);
    }


    /*@RequestMapping (value = "/cancle")
    @Operation(summary = "设备维修-取消", description = "设备维修-取消")
    public Result<?> cancle(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.cancle(equipmentRepair);
    }*/

    @RequestMapping (value = "/veto")
    @Operation(summary = "设备维修-否决", description = "设备维修-否决")
    public Result<?> veto(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.veto(equipmentRepair);
    }

    @RequestMapping (value = "/shut")
    @Operation(summary = "设备维修-关闭（异常）", description = "设备维修-关闭（异常）")
    public Result<?> shut(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.shut(equipmentRepair);
    }

    /**
     * 编辑
     *
     * @param equipmentRepair
     * @return
     */
    @Operation(summary = "设备维修-编辑", description = "设备维修-编辑", method = "PUT")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody EquipmentRepair equipmentRepair) {
        try {
            equipmentRepairService.updateRepairById(equipmentRepair);
        } catch (MBootException e) {
            return Result.error(e.getMessage());
        }
        return Result.OK("编辑成功!");
    }

    @Operation(summary = "设备维修-编辑-管理员", description = "设备维修-编辑-管理员", method = "PUT")
    @PutMapping(value = "/admin/edit")
    public Result<?> adminEdit(@RequestBody EquipmentRepair equipmentRepair) {
        try {
            equipmentRepairService.updateAdminRepairById(equipmentRepair);
        } catch (MBootException e) {
            return Result.error(e.getMessage());
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 派工
     *
     * @param equipmentRepair
     * @return
     */
    @Operation(summary = "设备维修-派工", description = "设备维修-派工", method = "PUT")
    @PutMapping(value = "/send")
    public Result<?> send(@RequestBody EquipmentRepair equipmentRepair) {
        try {
            equipmentRepairService.sendRepairById(equipmentRepair);
        } catch (MBootException e) {
            return Result.error(e.getMessage());
        }
        return Result.OK("派工成功!");
    }

    /**
     * 抢单
     *
     * @param equipmentRepair
     * @return
     */
    @Operation(summary = "设备维修-抢单", description = "设备维修-抢单", method = "PUT")
    @PutMapping(value = "/grab")
    public Result<?> grab(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.grabRepairById(equipmentRepair);
        return Result.OK("抢单成功!");
    }

    /**
     * 改派
     *
     * @param reason 改派原因
     * @param userId 改派人
     * @return
     */
    @Operation(summary = "设备维修-改派", description = "设备维修-改派", method = "PUT")
    @PutMapping(value = "/reSend")
    public Result<?> reSend(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.reSendRepairById(equipmentRepair.getReason(), equipmentRepair.getDistributePersonId(), equipmentRepair.getBizNo());
        return Result.OK("改派成功!");
    }

    /**
     * 开始维修
     *
     * @param id 维修ID
     * @return
     */
    @Operation(summary = "设备维修-开始维修", description = "设备维修-开始维修", method = "PUT")
    @PutMapping(value = "/start")
    public Result<?> start(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.start(equipmentRepair);
        return Result.OK("开始维修!");
    }

    /**
     * 维修结束
     *完成
     * @param id 维修ID
     * @return
     */
    @Operation(summary = "设备维修-维修结束", description = "设备维修-维修结束", method = "PUT")
    @PutMapping(value = "/finish")
    public Result<?> finish(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.finish(equipmentRepair);
        return Result.OK("维修结束!");
    }

    /**
     * 暂停
     *
     * @param reason 暂停原因
     * @param id
     * @return
     */
    @Operation(summary = "设备维修-暂停", description = "设备维修-暂停", method = "PUT")
    @PutMapping(value = "/stop")
    public Result<?> stop(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.stopRepairById(equipmentRepair.getReason(),equipmentRepair.getBizNo());
        return Result.OK("暂停成功!");
    }

    /**
     * 暂停结束
     *
     * @param id 维修ID
     * @return
     */
    @Operation(summary = "设备维修-暂停结束", description = "设备维修-暂停结束", method = "PUT")
    @PutMapping(value = "/end")
    public Result<?> endStop(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.endStop(equipmentRepair.getBizNo());
        return Result.OK("暂停结束!");
    }

    /**
     * 验收完成
     *
     * @param id 维修ID
     * @return
     */
    @Operation(summary = "设备维修-验收", description = "设备维修-验收", method = "PUT")
    @PutMapping(value = "/check")
    public Result<?> check(@RequestBody EquipmentRepair equipmentRepair ,HttpServletRequest request) {
        return equipmentRepairService.check(equipmentRepair );
    }

    /**
     * 验收驳回
     *
     * @param id 维修ID
     * @return
     */
    @Operation(summary = "设备维修-验收驳回", description = "设备维修-验收驳回", method = "PUT")
    @PutMapping(value = "/reject")
    public Result<?> reject(@RequestBody EquipmentRepair equipmentRepair) {
        equipmentRepairService.reject(equipmentRepair.getBizNo(), equipmentRepair.getReason());
        return Result.OK("验收驳回!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "设备维修-通过bizNo删除", description = "设备维修-通过bizNo删除", method = "DELETE")
    @DeleteMapping(value = "/delete/{bizNo}")
    public Result<?> delete(@PathVariable(name = "bizNo") String bizNo) {
        equipmentRepairService.delMain(bizNo);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Operation(summary = "设备维修-批量删除", description = "设备维修-批量删除", method = "DELETE")
    @DeleteMapping(value = "/deleteBatch/{bizNos}")
    public Result<?> deleteBatch(@PathVariable(name = "bizNos") String bizNos) {
        this.equipmentRepairService.delBatchMain(Arrays.asList(bizNos.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
//    @RequestMapping(value = "/exportXls")
//    public ModelAndView exportXls(HttpServletRequest request, TpmRepair equipmentRepair) {
//        return super.exportXls(request, equipmentRepair, TpmRepair.class, "设备维修");
//    }

    /**
     * 导出PDF
     * @param request
     * @return
     */
//    @RequestMapping(value = "/exportPdf")
//    protected ModelAndView exportPdf(HttpServletRequest request, TpmRepair equipmentRepair) {
//        QueryWrapper<TpmRepair> queryWrapper = QueryGenerator.initQueryWrapper(equipmentRepair, request.getParameterMap());
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        List<TpmRepair> queryList = equipmentRepairService.list(queryWrapper);
//        List<TpmRepair> exportList = null;
//        String selections = request.getParameter("selections");
//        if (oConvertUtils.isNotEmpty(selections)) {
//            List<String> selectionList = Arrays.asList(selections.split(","));
//            exportList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
//        } else {
//            exportList = queryList;
//        }
//        // Step.3 组装pageList
//        List<TpmRepairExport> pageList = new ArrayList<>();
//        //查询出字典数据
//        // 1.维修状态
//        Map<Integer,String> orderStatusMap = new HashMap<>();
//        List<DictModel> orderStatusList = sysDictService.queryDictItemsByCode("equipment_repair_status");;
//        if (orderStatusList != null && orderStatusList.size()>0){
//            orderStatusList.forEach(dictModel ->{
//                orderStatusMap.put(Integer.valueOf(dictModel.getValue()), dictModel.getText());
//            });
//        }
//        // 2.组别
//        Map<String,String> orgIdMap = new HashMap<>();
//        List<DictModel> orgIdList = sysDictService.queryTableDictItemsByCode("v_depart_group","name","id");
//        if (orgIdList != null && orgIdList.size()>0){
//            orgIdList.forEach(dictModel ->{
//                orgIdMap.put(dictModel.getValue(), dictModel.getText());
//            });
//        }
//        for (TpmRepair main : exportList){
//            TpmRepairExport vo = new TpmRepairExport();
//            BeanUtils.copyProperties(main, vo);
//            //处理字典字段
//            //申请人
//            SysUser user = sysUserMapper.getUserByName(vo.getApplyId());
//            if (user != null){
//                vo.setApplyName(user.getRealname());
//            }
//            //维修状态
//            vo.setOrderStatusText(orderStatusMap.get(vo.getOrderStatus()));
//            //组别
//            vo.setOrgIdText(orgIdMap.get(vo.getOrgId()));
//            //组负责人
//            SysUser user1 = sysUserMapper.getUserByName(vo.getRecePersonId());
//            if (user1 != null){
//                vo.setRecePersonIdText(user1.getRealname());
//            }
//            //维修人
//            SysUser user2 = sysUserMapper.getUserByName(vo.getDistributePersonId());
//            if (user2 != null){
//                vo.setDistributePersonIdText(user2.getRealname());
//            }
//            pageList.add(vo);
//        }
//        // 自定义视图 导出pdf
//        Map<String, Object> model = new HashMap<>();
//        model.put("sheet", pageList);
//        ModelAndView mv = new ModelAndView(new PdfView());
//        mv.addObject("data",model);
//        mv.addObject("title","维修履历数据");
//        mv.addObject("user",sysUser.getRealname());
//        mv.addObject("entity",TpmRepairExport.class);
//        return mv;
//    }

    /**
     * 导入
     *
     * @return
     */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, TpmRepair.class);
//    }
    /*---------------------------------主表处理-end-------------------------------------*/


    /*--------------------------------子表处理-维修操作历史-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @Operation(summary = "维修操作历史-通过主表ID查询", description = "维修操作历史-通过主表ID查询", method = "GET")
    @GetMapping(value = "/listTpmRepairOperationByMainId")
    public Result<?> listTpmRepairOperationByMainId(@Parameter(description = "查询参数") Criteria criteria,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {

        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<EquipmentRepairOperation> operations = equipmentRepairOperationService.listPage(EquipmentRepairOperation.class, page, criteria);
        return Result.OK(operations);
    }

    @Operation(summary = "维修操作历史-通过主表ID查询（不分页）", description = "维修操作历史-通过主表ID查询（不分页）", method = "GET")
    @GetMapping(value = "/listAllTpmRepairOperationByMainId/{mainId}")
    public Result<?> listAllTpmRepairOperationByMainId( @PathVariable(name = "mainId") String mainId,HttpServletRequest req) {
        Criteria criteria = Criteria.create();
        criteria.addCriterion("bizNo",Operator.EQ,mainId);
        List<EquipmentRepairOperation> operations = equipmentRepairOperationService.list(EquipmentRepairOperation.class,  criteria);
        return Result.OK(operations);
    }
    /**
     * 添加
     *
     * @param equipmentRepairOperation
     * @return
     */
    @Operation(summary = "维修操作历史-添加", description = "维修操作历史-添加", method = "POST")
    @PostMapping(value = "/addTpmRepairOperation")
    public Result<?> addTpmRepairOperation(@RequestBody EquipmentRepairOperation equipmentRepairOperation) {
        equipmentRepairOperationService.save(equipmentRepairOperation);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param equipmentRepairOperation
     * @return
     */
    @Operation(summary = "维修操作历史-编辑", description = "维修操作历史-编辑", method = "PUT")
    @PutMapping(value = "/editTpmRepairOperation")
    public Result<?> editTpmRepairOperation(@RequestBody EquipmentRepairOperation equipmentRepairOperation) {
        equipmentRepairOperationService.update(equipmentRepairOperation);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "维修操作历史-通过id删除", description = "维修操作历史-通过id删除", method = "DELETE")
    @DeleteMapping(value = "/deleteTpmRepairOperation")
    public Result<?> deleteTpmRepairOperation(@RequestParam(name = "id", required = true) String id) {
        equipmentRepairOperationService.delete(EquipmentRepairOperation.class,id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/deleteBatchTpmRepairOperation")
    @Operation(summary = "维修操作历史-批量删除", description = "维修操作历史-批量删除", method = "DELETE")
    public Result<?> deleteBatchTpmRepairOperation(@RequestParam(name = "ids", required = true) String ids) {
        Criteria criteria = Criteria.create();
        criteria.addCriterion("id", Operator.IN,Arrays.asList(ids.split(",")));
        this.equipmentRepairOperationService.removeBatch(EquipmentRepairOperation.class,criteria);
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
//    @RequestMapping(value = "/exportTpmRepairOperation")
//    public ModelAndView exportTpmRepairOperation(HttpServletRequest request, TpmRepairOperation equipmentRepairOperation) {
//        // Step.1 组装查询条件
//        QueryWrapper<TpmRepairOperation> queryWrapper = QueryGenerator.initQueryWrapper(equipmentRepairOperation, request.getParameterMap());
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//        // Step.2 获取导出数据
//        List<TpmRepairOperation> pageList = equipmentRepairOperationService.list(queryWrapper);
//        List<TpmRepairOperation> exportList = null;
//
//        // 过滤选中数据
//        String selections = request.getParameter("selections");
//        if (oConvertUtils.isNotEmpty(selections)) {
//            List<String> selectionList = Arrays.asList(selections.split(","));
//            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
//        } else {
//            exportList = pageList;
//        }
//
//        // Step.3 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        mv.addObject(NormalExcelConstants.FILE_NAME, "维修操作历史"); //此处设置的filename无效 ,前端会重更新设置一下
//        mv.addObject(NormalExcelConstants.CLASS, TpmRepairOperation.class);
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("维修操作历史报表", "导出人:" + sysUser.getRealname(), "维修操作历史"));
//        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
//        return mv;
//    }

    /**
     * 导入
     *
     * @return
     */
//    @RequestMapping(value = "/importTpmRepairOperation/{mainId}")
//    public Result<?> importTpmRepairOperation(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            MultipartFile file = entity.getValue();// 获取上传文件对象
//            ImportParams params = new ImportParams();
//            params.setTitleRows(2);
//            params.setHeadRows(1);
//            params.setNeedSave(true);
//            try {
//                List<TpmRepairOperation> list = ExcelImportUtil.importExcel(file.getInputStream(), TpmRepairOperation.class, params);
//                for (TpmRepairOperation temp : list) {
//                    temp.setRepairId(mainId);
//                }
//                long start = System.currentTimeMillis();
//                equipmentRepairOperationService.saveBatch(list);
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
//                return Result.OK("文件导入成功！数据行数：" + list.size());
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//                return Result.error("文件导入失败:" + e.getMessage());
//            } finally {
//                try {
//                    file.getInputStream().close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return Result.error("文件导入失败！");
//    }

    /*--------------------------------子表处理-维修操作历史-end----------------------------------------------*/

    /*--------------------------------子表处理-维修转单历史-begin----------------------------------------------*/

    /**
     * 通过主表ID查询
     *
     * @return
     */
    @GetMapping(value = "/listTpmRepairTransferByMainId")
    @Operation(summary = "维修操作历史-通过主表ID查询", description = "维修操作历史-通过主表ID查询", method = "GET")
    public Result<?> listTpmRepairTransferByMainId(@Parameter(description = "查询条件") Criteria criteria,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<EquipmentRepairTransfer> pageList = equipmentRepairTransferService.listPage(EquipmentRepairTransfer.class,page, criteria);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param equipmentRepairTransfer
     * @return
     */
    @PostMapping(value = "/addTpmRepairTransfer")
    @Operation(summary = "维修转单历史-添加", description = "维修转单历史-添加", method = "POST")
    public Result<?> addTpmRepairTransfer(@RequestBody EquipmentRepairTransfer equipmentRepairTransfer) {
        equipmentRepairTransferService.save(equipmentRepairTransfer);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param equipmentRepairTransfer
     * @return
     */
    @Operation(summary = "维修转单历史-编辑", description = "维修转单历史-编辑", method = "PUT")
    @PutMapping(value = "/editTpmRepairTransfer")
    public Result<?> editTpmRepairTransfer(@RequestBody EquipmentRepairTransfer equipmentRepairTransfer) {
        equipmentRepairTransferService.update(equipmentRepairTransfer);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @Operation(summary = "维修转单历史-通过id删除", description = "维修转单历史-通过id删除", method = "DELETE")
    @DeleteMapping(value = "/deleteTpmRepairTransfer")
    public Result<?> deleteTpmRepairTransfer(@RequestParam(name = "id", required = true) String id) {
        equipmentRepairTransferService.delete(EquipmentRepairTransfer.class,id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @Operation(summary = "维修转单历史-批量删除", description = "维修转单历史-批量删除", method = "DELETE")
    @DeleteMapping(value = "/deleteBatchTpmRepairTransfer")
    public Result<?> deleteBatchTpmRepairTransfer(@RequestParam(name = "ids", required = true) String ids) {
        Criteria criteria = Criteria.create();
        criteria.addCriterion("id", Operator.IN,Arrays.asList(ids.split(",")));
        this.equipmentRepairTransferService.deleteBatch(EquipmentRepairTransfer.class,criteria);
        return Result.OK("批量删除成功!");
    }

    /**
     * 导出
     *
     * @return
     */
//    @RequestMapping(value = "/exportTpmRepairTransfer")
//    public ModelAndView exportTpmRepairTransfer(HttpServletRequest request, TpmRepairTransfer equipmentRepairTransfer) {
//        // Step.1 组装查询条件
//        QueryWrapper<TpmRepairTransfer> queryWrapper = QueryGenerator.initQueryWrapper(equipmentRepairTransfer, request.getParameterMap());
//        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//        // Step.2 获取导出数据
//        List<TpmRepairTransfer> pageList = equipmentRepairTransferService.list(queryWrapper);
//        List<TpmRepairTransfer> exportList = null;
//
//        // 过滤选中数据
//        String selections = request.getParameter("selections");
//        if (oConvertUtils.isNotEmpty(selections)) {
//            List<String> selectionList = Arrays.asList(selections.split(","));
//            exportList = pageList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
//        } else {
//            exportList = pageList;
//        }
//
//        // Step.3 AutoPoi 导出Excel
//        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
//        mv.addObject(NormalExcelConstants.FILE_NAME, "维修转单历史"); //此处设置的filename无效 ,前端会重更新设置一下
//        mv.addObject(NormalExcelConstants.CLASS, TpmRepairTransfer.class);
//        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("维修转单历史报表", "导出人:" + sysUser.getRealname(), "维修转单历史"));
//        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
//        return mv;
//    }

    /**
     * 导入
     *
     * @return
     */
//    @RequestMapping(value = "/importTpmRepairTransfer/{mainId}")
//    public Result<?> importTpmRepairTransfer(HttpServletRequest request, HttpServletResponse response, @PathVariable("mainId") String mainId) {
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
//        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
//            MultipartFile file = entity.getValue();// 获取上传文件对象
//            ImportParams params = new ImportParams();
//            params.setTitleRows(2);
//            params.setHeadRows(1);
//            params.setNeedSave(true);
//            try {
//                List<TpmRepairTransfer> list = ExcelImportUtil.importExcel(file.getInputStream(), TpmRepairTransfer.class, params);
//                for (TpmRepairTransfer temp : list) {
//                    temp.setRepairId(mainId);
//                }
//                long start = System.currentTimeMillis();
//                tpmRepairTransferService.saveBatch(list);
//                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
//                return Result.OK("文件导入成功！数据行数：" + list.size());
//            } catch (Exception e) {
//                log.error(e.getMessage(), e);
//                return Result.error("文件导入失败:" + e.getMessage());
//            } finally {
//                try {
//                    file.getInputStream().close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        return Result.error("文件导入失败！");
//    }

    /*--------------------------------子表处理-维修转单历史-end----------------------------------------------*/
    @RequestMapping ("getNowadaysList/{areaid}")
    @Operation(summary = "根据一级areaid获取当天所有的维修单", description = "根据一级areaid获取当天所有的维修单", method = "GET")
    public Result<List<EquipmentRepair>> getNowadaysListByAreaid(@PathVariable(name = "areaid", required = true) String areaid) {
        return equipmentRepairService.getNowadaysListByAreaid(areaid);
    }


    @RequestMapping ("getSevendaysCntGroupbyFaultType/{areaid}")
    @Operation(summary = "根据一级areaid，统计七天内的维修单，并按故障类型分组统计", description = "根据一级areaid，统计七天内的维修单，并按故障类型分组统计", method = "GET")
    public Result<List<Map<String,Object>>> getSevendaysCntGroupbyFaultType(@PathVariable(name = "areaid", required = true) String areaid) {
        return equipmentRepairService.getSevendaysCntGroupbyFaultType(areaid);
    }

    @RequestMapping ("getSevendaysCntGroupbySecondArea/{areaid}")
    @Operation(summary = "根据一级areaid，统计七天内的维修单，并按二级区域分组统计", description = "根据一级areaid，统计七天内的维修单，并按二级区域分组统计", method = "GET")
    public Result<List<Map<String,Object>>> getSevendaysCntGroupbySecondArea(@PathVariable(name = "areaid", required = true) String areaid) {
        return equipmentRepairService.getSevendaysCntGroupbySecondArea(areaid);
    }


    @RequestMapping("excute/pickup/{bizNo}")
    @Operation(summary = "备件领料", description = "备件领料",method = "POST")
    public Result<List<EquipmentRepairPickupLine>> excute(@PathVariable(name = "bizNo", required = true) String bizNo,@RequestBody OrderExcuteVo orderExcuteVo) {
        EquipmentRepair order = equipmentRepairService.getById(EquipmentRepair.class, bizNo);
        /*if (order.getCloseStatus().equals(OrderStatusEnums.CloseStatus.CLOSED.getStatusCode())){
            return Result.error("关闭状态不能执行该操作");
        }
        if (order.getOrderStatus().equals(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode())){
            return Result.error("已完成状态不能执行该操作");
        }*/
        if (order.getRepairStatus().equals(EquipmentEnums.RepairStatus.REPORT.getCode())){
            return Result.error("已维修完成状态不能执行该操作");
        }
        return equipmentRepairService.executePickUp(order, orderExcuteVo.getLines());
    }

    @RequestMapping("excute/return/{bizNo}")
    @Operation(summary = "备件已领料退料", description = "备件已领料退料",method = "POST")
    public Result<Object> excuteReturn(@PathVariable(name = "bizNo", required = true) String bizNo,@RequestBody OrderExcuteVo orderExcuteVo) {
        EquipmentRepair order = equipmentRepairService.getById(EquipmentRepair.class, bizNo);
        /*if (order.getCloseStatus().equals(OrderStatusEnums.CloseStatus.CLOSED.getStatusCode())){
            return Result.error("关闭状态不能执行该操作");
        }
        if (order.getOrderStatus().equals(OrderStatusEnums.OrderStatus.FINISHED.getStatusCode())){
            return Result.error("已完成状态不能执行该操作");
        }*/
        if (order.getRepairStatus().equals(EquipmentEnums.RepairStatus.ZIPPED.getCode())){
            return Result.error("已归档状态不能执行该操作");
        }
        return equipmentRepairService.executeReturn(order, orderExcuteVo.getLines());
    }

    //先完成，再提交
    @RequestMapping (value = "/submit")
    @Operation(summary = "设备维修-提交", description = "设备维修-提交")
    public Result<?> submit(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.submit(equipmentRepair);
    }

    @RequestMapping (value = "/change",method = RequestMethod.POST)
    @Operation(summary = "设备维修-变更", description = "设备维修-变更")
    public Result<?> change(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.change(equipmentRepair);
    }

    @RequestMapping (value = "/confirm")
    @Operation(summary = "设备维修-主管确认", description = "设备维修-主管确认")
    public Result<?> confirm(@RequestBody EquipmentRepair equipmentRepair) {
        return equipmentRepairService.confirm(equipmentRepair);
    }

    // 当月故障设备TOP10
    @GetMapping("faultyEquipment")
    @Operation(summary = "当月故障设备TOP10", description = "当月故障设备TOP10", method = "GET")
    public Result<List<Map<String, Object>>>  faultyEquipment(@Parameter(description="查询参数") Criteria criteria) {
        List<Map<String, Object>> listTOP = equipmentRepairService.listTOP(criteria);
        return Result.OK(listTOP);
    }

//    //当月的长停机概览，总停机时长
//    @RequestMapping("totalMentions")
//    @Operation(summary = "当月的长停机概览，总停机时长", description = "当月的长停机概览，总停机时长")
//    public Result<?> getTheTotalDowntime(@Parameter(description="查询参数") Criteria criteria){
//        equipmentRepairService.getTheTotalDowntime(criteria);
//        return Result.OK();
//    }

    @GetMapping("/page/totalMentions")
    @Operation(summary = "repair列表(包含-当月的长停机概览，总停机时长）", description = "获取repair列表（分页）(包含-当月的长停机概览，总停机时长）", method = "GET")
    public Result<Page<EquipmentRepair>> getTheTotalDowntimePage(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) {
        equipmentRepairService.getTheTotalDowntime();
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<EquipmentRepair> pageResult = equipmentRepairService.listPage(EquipmentRepair.class, page, criteria);
        return Result.OK(pageResult);
    }

    @PutMapping("/isEvaluate")
    @Operation(summary = "评价不通过，打回提交状态", description = "评价不通过，打回提交状态", method = "PUT")
    public Result<EquipmentRepair> isEvaluate(@RequestBody EquipmentRepair equipmentRepair ) {
        EquipmentRepair evaluate = equipmentRepairService.isEvaluate(equipmentRepair);
        return Result.OK(evaluate);
    }


}
